package com.share.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.share.common.core.utils.StringUtils;
import com.share.device.domain.Cabinet;
import com.share.device.domain.Station;
import com.share.device.domain.StationLocation;
import com.share.device.domain.StationVo;
import com.share.device.service.ICabinetService;
import com.share.device.service.IDeviceService;
import com.share.device.service.IStationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class DeviceServiceImpl implements IDeviceService {


    @Autowired
    private IStationService stationService;

    @Autowired
    private ICabinetService cabinetService;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询附近的站点设备列表
     * @param latitude
     * @param longitude
     * @param radius
     * @return
     */
    @Override
    public List<StationVo> nearbyStationList(String latitude, String longitude, Integer radius) {
        // 坐标确认中心点
        GeoJsonPoint geoJsonPoint = new GeoJsonPoint(Double.parseDouble(longitude), Double.parseDouble(latitude));
        // 半径
        Distance distance = new Distance(radius, Metrics.KILOMETERS);
        // 画圆圈
        Circle circle = new Circle(geoJsonPoint,distance);

        Query query = Query.query(Criteria.where("location").withinSphere(circle));
        List<StationLocation> stationLocations = mongoTemplate.find(query, StationLocation.class);
        if (CollectionUtils.isEmpty(stationLocations)) return null;
        // 查询附近的站点、封装数据返回
        List<StationVo> stationVos = new ArrayList<>();
        List<Long> stationIdList = stationLocations.stream().map(StationLocation::getStationId).collect(Collectors.toList());
        // 查询站点信息
        List<Station> stationList = stationService.list(new LambdaQueryWrapper<Station>().in(Station::getId, stationIdList).isNotNull(Station::getCabinetId));

        List<Long> cabinetIdList = stationList.stream().map(Station::getCabinetId).collect(Collectors.toList());
        //获取柜机id与柜机信息Map
        Map<Long, Cabinet> cabinetIdToCabinetMap = cabinetService.listByIds(cabinetIdList).stream().collect(Collectors.toMap(Cabinet::getId, Cabinet -> Cabinet));

        //数据封装
        stationList.forEach(station -> {
            StationVo stationVo = new StationVo();
            BeanUtils.copyProperties(station, stationVo);

            //获取柜机信息
            Cabinet cabinet = cabinetIdToCabinetMap.get(station.getCabinetId());
            if (StringUtils.isNotNull(cabinet)){
                //可用充电宝数量大于0，可借用
                if(cabinet.getAvailableNum() > 0) {
                    stationVo.setIsUsable("1");
                } else {
                    stationVo.setIsUsable("0");
                }
                // 获取空闲插槽数量大于0，可归还
                if (cabinet.getFreeSlots() > 0) {
                    stationVo.setIsReturn("1");
                } else {
                    stationVo.setIsReturn("0");
                }
                stationVos.add(stationVo);
            }
        });
        return stationVos;
    }
}
